package hkr.vfu.bluecenter.activities;

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import hkr.vfu.bluecenter.R;
import hkr.vfu.bluecenter.backend.BluetoothSingleton;
import hkr.vfu.bluecenter.backend.BoxVO;
import hkr.vfu.bluecenter.backend.DataSingleton;
import hkr.vfu.bluecenter.swipe_fragments.BluecenterFragment;

/**
 * Created by mattiasbowallius on 31/10/13.
 */
public class SettingsActivity extends Activity implements BluecenterFragment, Button.OnClickListener {

    private File runButtonScriptFile;
    private File initContinuousFile;
    private File repetitiveContinuousFile;
    private File endContinuousFile;
    private File hashMapFile;
    private String MAC;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.settings_fragment);

        MAC = getIntent().getStringExtra("MAC");

        runButtonScriptFile = new File(getFilesDir() + "Run_Button_Script.txt");
        initContinuousFile = new File(getFilesDir() + "Init_Continuous_Script.txt");
        repetitiveContinuousFile = new File(getFilesDir() + "Repetitive_Continous_Script.txt");
        endContinuousFile = new File(getFilesDir() + "End_Continous_Script.txt");

        hashMapFile = new File(getFilesDir(), "hashMap");
        if (!hashMapFile.exists()) {
            try {
                hashMapFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        initializeButtons();
    }

    @Override
    public void onStart() {
        super.onStart();
        updateUI();
    }

    @Override
    public void onResume() {
        super.onResume();
        updateUI();
    }

    private void addSaveButtonListener() {
        saveSingleRunScript();
        saveInitScript();
        saveRepetitiveScript();
        saveEndingScript();
        if (BluetoothSingleton.getInstance().isConnected(MAC)) saveLogFileName();
        BluetoothSingleton bluetoothSingleton = BluetoothSingleton.getInstance();
        if (bluetoothSingleton.isConnected(MAC)) {
            DataSingleton dataSingleton = DataSingleton.getInstance();
            dataSingleton.getBoxWithMAC(MAC)
                    .setNumberOfSensors(Integer.parseInt(((EditText) findViewById(R.id.number_of_sensors_editText))
                            .getText()
                            .toString()));
            EditText renameField = (EditText) findViewById(R.id.rename_bluetooth_device_field);
            dataSingleton.getBoxWithMAC(MAC)
                    .setName(renameField.getText().toString());
        }
    }

    private void saveSingleRunScript() {
        try {
            BufferedWriter out = new BufferedWriter(new FileWriter(runButtonScriptFile));
            EditText commandField = (EditText) findViewById(R.id.run_button_script_field);
            Editable command = commandField.getText();
            char[] commandString = new char[command.length()];
            if (command != null) {
                command.getChars(0, command.length(), commandString, 0);
            }
            out.write(commandString);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void saveInitScript() {
        try {
            BufferedWriter out = new BufferedWriter(new FileWriter(initContinuousFile));
            EditText commandField = (EditText) findViewById(R.id.initializer_editText);
            Editable command = commandField.getText();
            char[] commandString = new char[command.length()];
            if (command != null) {
                command.getChars(0, command.length(), commandString, 0);
            }
            out.write(commandString);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void saveRepetitiveScript() {
        try {
            BufferedWriter out = new BufferedWriter(new FileWriter(repetitiveContinuousFile));
            EditText commandField = (EditText) findViewById(R.id.repetitive_editText);
            Editable command = commandField.getText();
            char[] commandString = new char[command.length()];
            if (command != null) {
                command.getChars(0, command.length(), commandString, 0);
            }
            out.write(commandString);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void saveEndingScript() {
        try {
            BufferedWriter out = new BufferedWriter(new FileWriter(endContinuousFile));
            EditText commandField = (EditText) findViewById(R.id.ending_editText);
            Editable command = commandField.getText();
            char[] commandString = new char[command.length()];
            if (command != null) {
                command.getChars(0, command.length(), commandString, 0);
            }
            out.write(commandString);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void saveLogFileName() {
        EditText commandField = (EditText) findViewById(R.id.name_of_log_file_editText);
        Editable command = commandField.getText();
        String name = command.toString();
        BoxVO currentBoxVO = DataSingleton.getInstance()
                .getBoxWithMAC(MAC);
        currentBoxVO.setLogName(name);
    }

    @Override
    public void updateUI() {
        loadFilesIntoViews();
        updateNameAndSensorNumber();
    }

    private void updateNameAndSensorNumber() {
        EditText numberOfSensorsField = (EditText) findViewById(R.id.number_of_sensors_editText);
        if (BluetoothSingleton.getInstance().isConnected(MAC)) {
            DataSingleton dataSingleton = DataSingleton.getInstance();
            readLogFileName();
            int numberOfSensorsOnBox = dataSingleton.getBoxWithMAC(MAC)
                    .getSensors().length;
            numberOfSensorsField.setText(String.valueOf(numberOfSensorsOnBox));
            String bluetoothName = dataSingleton.getBoxWithMAC(MAC)
                    .getName();
            EditText bluetoothNameField = (EditText) findViewById(R.id.rename_bluetooth_device_field);
            bluetoothNameField.setText(bluetoothName);
        } else {
            numberOfSensorsField.setText("0");
        }
    }

    private void loadFilesIntoViews() {
        readFromFileIntoView(runButtonScriptFile, R.id.run_button_script_field);
        readFromFileIntoView(initContinuousFile, R.id.initializer_editText);
        readFromFileIntoView(repetitiveContinuousFile, R.id.repetitive_editText);
        readFromFileIntoView(endContinuousFile, R.id.ending_editText);
    }

    private void readFromFileIntoView(File file, int viewID) {
        try {
            BufferedReader in = new BufferedReader(new FileReader(file));
            StringBuilder builder = new StringBuilder();
            String line;
            boolean first = true;
            while ((line = in.readLine()) != null) {
                if (!first) {
                    builder.append("\n");
                }
                builder.append(line);
                first = false;
            }
            in.close();
            EditText commandField = (EditText) findViewById(viewID);
            commandField.setText(builder.toString());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void readLogFileName() {
        BoxVO currentBoxVO = DataSingleton.getInstance()
                .getBoxWithMAC(MAC);
        EditText commandField = (EditText) findViewById(R.id.name_of_log_file_editText);
        commandField.setText(currentBoxVO.getLogName());
    }

    private void initializeButtons() {
        ImageButton saveChangedSettingsButton = (ImageButton) findViewById(R.id.save_changed_settings_button);
        saveChangedSettingsButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.save_changed_settings_button:
                addSaveButtonListener();
                finish();
                break;

        }
    }
}
